package com.cby.code.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;

/**
 * Description:ResourcesUtils
 *
 * @author 陈宝阳
 * @create 2020/8/3 17: 09
 */
public class ResourcesUtils {

  private static final String RES_ID = "id";
  private static final String RES_STRING = "string";
  private static final String RES_DRAWABLE = "drawable";
  private static final String RES_LAYOUT = "layout";
  private static final String RES_STYLE = "style";
  private static final String RES_COLOR = "color";
  private static final String RES_DIMEN = "dimen";
  private static final String RES_ANIM = "anim";
  private static final String RES_MENU = "menu";

  public ResourcesUtils() {
  }

  public static int getId(Context context, String resName) {
    return getResId(context, resName, RES_ID);
  }

  public static int getStringId(Context context, String resName) {
    return getResId(context, resName, RES_STRING);
  }

  public static int getDrawableId(Context context, String resName) {
    return getResId(context, resName, RES_DRAWABLE);
  }

  public static int getLayoutId(Context context, String resName) {
    return getResId(context, resName, RES_LAYOUT);
  }

  public static int getStyleId(Context context, String resName) {
    return getResId(context, resName, RES_STYLE);
  }

  public static int getColorId(Context context, String resName) {
    return getResId(context, resName, RES_COLOR);
  }

  public static int getDimenId(Context context, String resName) {
    return getResId(context, resName, RES_DIMEN);
  }

  public static int getAnimId(Context context, String resName) {
    return getResId(context, resName, RES_ANIM);
  }

  public static int getMenuId(Context context, String resName) {
    return getResId(context, resName, RES_MENU);
  }

  public static int getResId(Context context, String resName, String defType) {
    return context.getResources().getIdentifier(resName, defType, context.getPackageName());
  }

  public static void setFontScale(Activity activity) {
    Resources resources = activity.getResources();
    Configuration newConfig = resources.getConfiguration();
    DisplayMetrics displayMetrics = resources.getDisplayMetrics();

    if (newConfig.fontScale != 1) {
      newConfig.fontScale = 1;
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Context configurationContext = activity.createConfigurationContext(newConfig);
        resources = configurationContext.getResources();
        displayMetrics.scaledDensity = displayMetrics.density * newConfig.fontScale;
      }
      resources.updateConfiguration(newConfig, displayMetrics);
    }
  }
}
